#include "turncontroller.h"
#include <QPainter>
#include <QMouseEvent>
#include <QtMath>
#include <QApplication>
#include <QPainterPath>

TurnController::TurnController(QWidget *parent)
    : QWidget(parent)
{
    setAttribute(Qt::WA_StyledBackground, true);
    setStyleSheet("background-color: transparent;");
}

void TurnController::paintEvent(QPaintEvent* /*event*/)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 计算中心点和尺寸
    m_center = rect().center();
    int width = this->width() - 10;  // 留出边距
    int height = this->height();  // 高度为控件高度的1/4
    m_radius = height / 2;  // 圆角半径

    // 计算矩形区域
    m_controlRect = QRect(
        m_center.x() - width/2,  // 左边
        m_center.y() - height/2,  // 顶部
        width,                    // 宽度
        height                    // 高度
    );

    // 绘制各个部分
    drawBackground(painter);
    drawCenterPoint(painter);
}

void TurnController::drawBackground(QPainter& painter)
{
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(18,18,18,100));
    painter.drawRoundedRect(m_controlRect, m_radius, m_radius);

    // 如果正在拖动，添加边缘高亮效果
    if (m_isDragging) {
        QPoint delta = m_currentPos - m_center;
        double ratio = qAbs(double(delta.x()) / (m_controlRect.width() / 2));
        ratio = qMin(1.0, ratio);

        QPainterPath path1;
        path1.addRoundedRect(m_controlRect, m_radius, m_radius);

        // 确定高亮位置
        QPoint highlightPos;
        if (delta.x() > 0) {
            highlightPos = QPoint(m_controlRect.right(), m_center.y());
        } else {
            highlightPos = QPoint(m_controlRect.left(), m_center.y());
        }

        // 创建径向渐变作为高亮点
        QRadialGradient highlightGradient(highlightPos, m_radius * 4);
        highlightGradient.setColorAt(0, QColor(0, 255, 255, ratio * 255));
        highlightGradient.setColorAt(1, QColor(0, 0, 0, 0));

        // 绘制高亮效果
        painter.setBrush(highlightGradient);
        painter.drawRoundedRect(m_controlRect, m_radius, m_radius);
    }
}

void TurnController::drawCenterPoint(QPainter& painter)
{
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::white);

    // 确保控制点不会超出边界
    QPoint drawPos = m_isDragging ? m_currentPos : m_center;
    
    // 如果控制点超出边界，调整其显示位置
    if (drawPos.x() < m_controlRect.left() + m_radius) {
        drawPos.setX(m_controlRect.left() + m_radius);
    } else if (drawPos.x() > m_controlRect.right() - m_radius) {
        drawPos.setX(m_controlRect.right() - m_radius);
    }
    if (m_isDragging) {
        QPixmap pixmap(":/images/ctrl_center_drag.png");
        QTransform transform;
        // 计算旋转角度 - 向左拖动时逆时针旋转90度,向右拖动时顺时针旋转90度
        QPoint delta = m_currentPos - m_center;
        double angle = delta.x() > 0 ? 90 : -90;
        transform.rotate(angle);
        QPixmap rotatedPixmap = pixmap.transformed(transform);
        painter.drawPixmap(drawPos.x() - m_radius, drawPos.y() - m_radius,
                         2 * m_radius, 2 * m_radius, rotatedPixmap);
    } else {
        QPixmap pixmap(":/images/ctrl_center.png"); 
        painter.drawPixmap(drawPos.x() - m_radius, drawPos.y() - m_radius,
                         2 * m_radius, 2 * m_radius, pixmap);
    } 
}

QPoint TurnController::limitToRect(const QPoint& pos)
{
    // 移除m_radius的限制，允许移动到矩形边缘
    int x = qBound(m_controlRect.left(), pos.x(), m_controlRect.right());
    int y = m_center.y();
    return QPoint(x, y);
}

void TurnController::calculateTurn(const QPoint& pos)
{
    QPoint delta = pos - m_center;
    m_turnSpeed = double(delta.x()) / (m_controlRect.width() / 2);
    m_turnSpeed = qBound(-1.0, m_turnSpeed, 1.0);
    emit turnChanged(m_turnSpeed);
}

void TurnController::startDragging(const QPoint& pos)
{
    // 将全局坐标转换为局部坐标
    QPoint localPos = mapFromParent(pos);
    
    // 开始拖动
    m_isDragging = true;
    m_currentPos = limitToRect(localPos);
    calculateTurn(m_currentPos);
    
    // 抓取鼠标
    grabMouse();
    update();
}

void TurnController::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isDragging) {
        // 获取当前位置，但只使用X坐标
        QPoint pos = event->pos();
        pos.setY(m_center.y());  // 固定Y坐标为中心点的Y坐标
        
        m_currentPos = limitToRect(pos);
        calculateTurn(m_currentPos);
        update();
    }
}

void TurnController::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_isDragging) {
        m_isDragging = false;
        m_currentPos = m_center;
        m_turnSpeed = 0.0;  // 重置速度
        emit turnChanged(0);
        releaseMouse();
        update();

        // 将释放事件传递给父窗口
        QPoint parentPos = mapTo(parentWidget(), event->pos());
        QMouseEvent *newEvent = new QMouseEvent(
            QEvent::MouseButtonRelease,
            parentPos,
            event->button(),
            event->buttons(),
            event->modifiers()
        );
        QApplication::postEvent(parentWidget(), newEvent);
    }
}

bool TurnController::event(QEvent *event)
{
    // 对于鼠标按下和释放事件，先传递给父窗口
    if (event->type() == QEvent::MouseButtonPress || 
        event->type() == QEvent::MouseButtonRelease) 
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        
        // 将局部坐标转换为父窗口坐标
        QPoint parentPos = mapTo(parentWidget(), mouseEvent->pos());
        
        // 创建新的鼠标事件
        QMouseEvent *newEvent = new QMouseEvent(
            mouseEvent->type(),
            parentPos,
            mouseEvent->button(),
            mouseEvent->buttons(),
            mouseEvent->modifiers()
        );
        
        // 发送到父窗口
        QApplication::postEvent(parentWidget(), newEvent);
        
        // 继续处理本控件的事件
        return QWidget::event(event);
    }
    
    return QWidget::event(event);
} 
